"""Lead model for Real Estate CRM system (客户管理)."""

from __future__ import annotations

from typing import TYPE_CHECKING
from uuid import UUID

from datetime import datetime
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text, Enum as SQLEnum
from sqlalchemy.orm import Mapped, mapped_column, relationship

from ..db.base_class import Base
from ..models.base import TimestampMixin
from ..models.enums import DemandType, SourceChannel, LeadStage, QualityGrade

if TYPE_CHECKING:
    from ..models.user import User
    from ..models.lead_contact import LeadContact
    from ..models.lead_note import LeadNote
    from ..models.lead_ai_summary import LeadAISummary
    from ..models.visitor_sheet import VisitorSheet
    from ..models.lead_tag import LeadTag
    from ..models.lead_intention import LeadIntention
    from ..models.follow_up_reminder import FollowUpReminder


class Lead(Base, TimestampMixin):
    """客户主表 - 房产CRM核心实体."""

    __tablename__ = "leads"

    id: Mapped[int] = mapped_column(primary_key=True, index=True)

    # 基本信息
    name: Mapped[str] = mapped_column(String(100), nullable=False, comment="客户姓名")
    phone: Mapped[str] = mapped_column(
        String(20), unique=True, index=True, nullable=False, comment="手机号（唯一）"
    )

    # 需求信息
    demand_type: Mapped[DemandType] = mapped_column(
        SQLEnum(DemandType), nullable=False, index=True, comment="需求类型"
    )
    budget_range: Mapped[str | None] = mapped_column(
        String(100), nullable=True, comment="预算范围（如: 4000-6000, 300-500万）"
    )

    # 来源与阶段
    source_channel: Mapped[SourceChannel] = mapped_column(
        SQLEnum(SourceChannel),
        nullable=False,
        index=True,
        default=SourceChannel.OTHER,
        comment="来源渠道",
    )
    stage: Mapped[LeadStage] = mapped_column(
        SQLEnum(LeadStage), nullable=False, default=LeadStage.NEW, index=True, comment="跟进阶段"
    )

    # 备注（AI标签提取源）
    notes: Mapped[str | None] = mapped_column(
        Text, nullable=True, comment="备注信息（AI将从此字段提取需求标签）"
    )

    # 标签快速搜索字段（冗余但高效）
    tag_names: Mapped[str | None] = mapped_column(
        String(500),
        nullable=True,
        index=True,
        comment="标签名快速搜索（逗号分隔）：'近地铁,学区房,安静'，最多3-4个",
    )

    # 客户质量评估（MVP1新增）
    quality_score: Mapped[int | None] = mapped_column(
        Integer,
        nullable=True,
        index=True,
        comment="客户质量分数（0-100）：基于5维度综合评分",
    )
    quality_grade: Mapped[QualityGrade | None] = mapped_column(
        SQLEnum(QualityGrade),
        nullable=True,
        index=True,
        comment="客户质量等级：S(90+)/A(80+)/B(70+)/C(60+)/D(<60)",
    )
    quality_updated_at: Mapped[datetime | None] = mapped_column(
        DateTime,
        nullable=True,
        comment="质量评分最后更新时间",
    )

    # 导入批次
    import_batch_id: Mapped[UUID] = mapped_column(
        nullable=False, index=True, comment="Excel导入批次ID"
    )

    # Foreign keys
    owner_id: Mapped[int] = mapped_column(
        ForeignKey("users.id"), nullable=False, index=True, comment="负责经纪人ID"
    )

    # Soft delete fields
    is_deleted: Mapped[bool] = mapped_column(
        Boolean, nullable=False, default=False, index=True, comment="软删除标记"
    )
    deleted_at: Mapped[datetime | None] = mapped_column(
        DateTime, nullable=True, comment="软删除时间戳"
    )
    deleted_by: Mapped[int | None] = mapped_column(
        Integer, nullable=True, comment="执行删除的用户ID"
    )

    # Relationships
    owner: Mapped[User] = relationship("User", back_populates="leads")
    contacts: Mapped[list[LeadContact]] = relationship(
        "LeadContact", back_populates="lead", cascade="all, delete-orphan"
    )
    lead_notes: Mapped[list[LeadNote]] = relationship(
        "LeadNote", back_populates="lead", cascade="all, delete-orphan"
    )
    ai_summaries: Mapped[list[LeadAISummary]] = relationship(
        "LeadAISummary", back_populates="lead", cascade="all, delete-orphan"
    )
    visitor_sheets: Mapped[list[VisitorSheet]] = relationship("VisitorSheet", back_populates="lead")
    lead_tags: Mapped[list[LeadTag]] = relationship(
        "LeadTag", back_populates="lead", cascade="all, delete-orphan"
    )
    intentions: Mapped[list[LeadIntention]] = relationship(
        "LeadIntention", back_populates="lead", cascade="all, delete-orphan", order_by="LeadIntention.priority"
    )
    reminders: Mapped[list[FollowUpReminder]] = relationship(
        "FollowUpReminder", back_populates="lead", cascade="all, delete-orphan"
    )
